package com.itdl.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author: itdl
 * @date: 2022/3/7 15:37
 * @description: 文件下载工具类
 * @version: 1.0
 */
public class DownloadUtil {
    /**
     * 文件下载
     * @param response 响应对象
     * @param bytes 字节数组
     * @param responseFileName 文件下载名称
     */
    public static void download(HttpServletResponse response, byte[] bytes, String responseFileName){
        ServletOutputStream outputStream = null;
        try {
            // 设置请求头和下载时的文件名
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(responseFileName, StandardCharsets.UTF_8.name()));
            // 设置编码
            response.setCharacterEncoding("UTF-8");
            // 获取输出流对象
            outputStream = response.getOutputStream();
            // 将文件流写入输出流
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 如果流不为空，刷新并关闭输出流
            if (outputStream != null){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
